#include "seu_port.h"
#include "seu_kernel.h"

void port_delay_us(seu_uint32_t delay_us)
{
    seu_uint32_t ticks;
    seu_uint32_t told, tnow, tcnt = 0;
    seu_uint32_t reload = SysTick->LOAD;
    ticks = delay_us * SEUClock_1US;
    told = SysTick->VAL;
    while(1){
        tnow = SysTick->VAL;
        if(tnow != told){
            if(tnow < told){
                tcnt += told - tnow;
            }else{
                tcnt += reload - tnow + told;
            }
            told = tnow;
            if(tcnt >= ticks) break;
        }
    }
}

void port_delay_ms(seu_uint32_t delay_ms)
{
    port_delay_us(delay_ms*1000);
}

void PORT_seu_systick_init(void)
{
    seu_uint32_t *Systick_priority = (seu_uint32_t*)0xE000ED23;
    SysTick->LOAD = SEUClock_1US * 1000;
    *Systick_priority = 0x00;
    SysTick->VAL = 0;
    SysTick->CTRL = 0x01;
}

void PORT_seu_systick_ctrl(seu_uint8_t sta)
{
    if(sta == SEU_TRUE){
        SysTick->CTRL |= 0x1;
    }else{
        SysTick->CTRL &= ~0x1;
    }
}

void PORT_seu_systick_irq_ctrl(seu_uint8_t sta)
{
    if(sta == SEU_TRUE){
        SysTick->CTRL |= 0x2;
    }else{
        SysTick->CTRL &= ~0x2;
    }
}

void SysTick_Handler(void) //定时器中断函数(移植时修改成对应的硬件定时器中断函数名)
{
    seu_systick_handler(); //系统的中断函数(依靠改名的中断函数来实现)
}

void PORT_seu_svc_init(void)
{
    //移植填充
	seu_uint32_t* NVIC_SYSPRI14 = (seu_uint32_t *)0xE000ED22;
	*NVIC_SYSPRI14 = 0xFF;
}

void PORT_seu_sched(void)
{
    PORT_seu_core_enter();
	seu_uint32_t* NVIC_INT_CTRL = (seu_uint32_t *)0xE000ED04;
    *NVIC_INT_CTRL = 0x10000000;
    PORT_seu_core_exit();
}
